package com.trainingcloud.action;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.struts2.ServletActionContext;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;


import com.opensymphony.xwork2.ActionSupport;
import com.trainingcloud.Globals;
import com.trainingcloud.exception.DAOException;
import com.trainingcloud.exception.SystemException;

public abstract class BaseAction extends ActionSupport 
{
	protected static final String NO_XML_RESPONSE = "NO_XML_RESPONSE";
	private String version;
	private Document responseDoc;
	protected Element responseElement;
	
	
	public BaseAction() throws SystemException
	{
		initResponseDoc();
	}
	
	private void initResponseDoc()
	{
		responseDoc = DocumentHelper.createDocument();
		responseElement = responseDoc.addElement("response");
	}
	
	protected void error(String message)
	{
		responseElement.addElement("error")
					   .addText(message);
	}
	
	public String execute() throws DAOException, SystemException
	{
		String result = null;
		if(Globals.isValidVersion(version))
		{
			error("Invalid client version.");
			result = "failure";
		}
		else
		{
			String message = call();
			if(message==null)
			{
				result = "success";
			}
			else if(message.compareTo(NO_XML_RESPONSE)==0)
			{
				return "success";
			}
			else
			{
				error(message);
				result = "failure";
			}
		}
		HttpServletResponse response = ServletActionContext.getResponse();         
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/xml;charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		try
		{
		    OutputFormat outFmt = new OutputFormat("\t", true);
		    outFmt.setEncoding("UTF-8");
		    XMLWriter output = new XMLWriter(response.getOutputStream(), outFmt);  
		    output.write(responseDoc);
		    output.close();
		}
		catch (IOException e)
		{
		    System.out.println(e.getMessage());
		}

		return null;
	}
	
	abstract public String call() throws DAOException, SystemException;
	
	public String getVersion() 
	{
		return version;
	}

	public void setVersion(String version) 
	{
		this.version = version;
	}
	
}
